package org.feisoft.jta.logging;

import org.feisoft.transaction.archive.TransactionArchive;
import org.feisoft.transaction.archive.XAResourceArchive;
import org.feisoft.transaction.logging.ArchiveDeserializer;
import org.feisoft.transaction.xa.TransactionId;

public class ArchiveDeserializerImpl implements ArchiveDeserializer
{
    static final byte TYPE_TRANSACTION = 0x0;
    static final byte TYPE_XA_RESOURCE = 0x1;

    private ArchiveDeserializer xaResourceArchiveDeserializer;
    private ArchiveDeserializer transactionArchiveDeserializer;

    public byte[] serialize(TransactionId xid, Object archive)
    {

        if (TransactionArchive.class.isInstance(archive))
        {
            byte[] array = this.transactionArchiveDeserializer.serialize(xid, archive);
            byte[] byteArray = new byte[array.length + 1];
            byteArray[0] = TYPE_TRANSACTION;
            System.arraycopy(array, 0, byteArray, 1, array.length);
            return byteArray;
        } else if (XAResourceArchive.class.isInstance(archive))
        {
            byte[] array = this.xaResourceArchiveDeserializer.serialize(xid, archive);
            byte[] byteArray = new byte[array.length + 1];
            byteArray[0] = TYPE_XA_RESOURCE;
            System.arraycopy(array, 0, byteArray, 1, array.length);
            return byteArray;
        } else
        {
            throw new IllegalArgumentException();
        }

    }

    public Object deserialize(TransactionId xid, byte[] array)
    {
        if (array == null || array.length <= 1)
        {
            throw new IllegalArgumentException();
        }

        byte type = array[0];
        if (type == TYPE_TRANSACTION)
        {
            byte[] byteArray = new byte[array.length - 1];
            System.arraycopy(array, 1, byteArray, 0, byteArray.length);
            return this.transactionArchiveDeserializer.deserialize(xid, byteArray);
        } else if (type == TYPE_XA_RESOURCE)
        {
            byte[] byteArray = new byte[array.length - 1];
            System.arraycopy(array, 1, byteArray, 0, byteArray.length);
            return this.xaResourceArchiveDeserializer.deserialize(xid, byteArray);
        } else
        {
            throw new IllegalArgumentException();
        }

    }

    public ArchiveDeserializer getXaResourceArchiveDeserializer()
    {
        return xaResourceArchiveDeserializer;
    }

    public void setXaResourceArchiveDeserializer(ArchiveDeserializer xaResourceArchiveDeserializer)
    {
        this.xaResourceArchiveDeserializer = xaResourceArchiveDeserializer;
    }

    public ArchiveDeserializer getTransactionArchiveDeserializer()
    {
        return transactionArchiveDeserializer;
    }

    public void setTransactionArchiveDeserializer(ArchiveDeserializer transactionArchiveDeserializer)
    {
        this.transactionArchiveDeserializer = transactionArchiveDeserializer;
    }

}
